package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MenuService;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import com.itheima.utils.SerializeUtil;
import com.qiniu.util.Json;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 菜单控制层
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private MenuService menuService;

    @Autowired
    private JedisPool jedisPool;


    /**
     * 菜单分页查询
     * XuJie
     */
    @RequestMapping(value = "/findPage", method = RequestMethod.POST)
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

        return menuService.findPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
    }

    /**
     * 增加编辑窗口一级菜单查询
     */
    @RequestMapping(value = "/findFirstMenu",method = RequestMethod.GET)
    public Result findFirstMenu(){
        try {
            List<Menu> menuList = menuService.findFirstMenu();

            return new Result(true,MessageConstant.GET_MENU_SUCCESS,menuList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MENU_FAIL);

        }
    }

    /**
     * 菜单新增
     * XuJie
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Result add(@RequestBody Menu menu,Integer[] roleIds){
        try {

            menuService.add(menu,roleIds);
            return new Result(true,MessageConstant.INSERT_MENU_SUCCESS);
        }catch(RuntimeException e){
            return new Result(false,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.INSERT_MENU_FAIL);
        }
    }

    @RequestMapping(value = "/findAllRoles",method = RequestMethod.GET)
    public Result findAllRoles(){
        try {
            List<Role> roleList = menuService.findAllRoles();
            return new Result(true,MessageConstant.QUERY_ROLE_SUCCESS,roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ROLE_FAIL);
        }

    }

    /**
     * 菜单编辑窗口数据回显
     * XuJie
     */
    @RequestMapping(value = "/findById",method = RequestMethod.GET)
    public Result findById(Integer menuId){
        try {

            Menu menu = menuService.findById(menuId);

            return new Result(true,MessageConstant.GET_MENU_SUCCESS,menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MENU_FAIL);

        }
    }

    /**
     * 菜单编辑
     * XuJie
     */
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public Result edit(@RequestBody Menu menu){
        try {
            //删除redis数据中的菜单缓存
            jedisPool.getResource().del("menu".getBytes());

            menuService.edit(menu);
            return new Result(true,MessageConstant.UPDATE_MENU_SUCCESS);
        }catch(RuntimeException e){
            return new Result(false,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.UPDATE_MENU_FAIL);
        }
    }

    /**
     * 菜单删除
     * XuJie
     */
    @RequestMapping(value = "/deleteById",method = RequestMethod.GET)
    public Result deleteById(Integer menuId){
        try {

            menuService.deleteById(menuId);
            return new Result(true,MessageConstant.DELETE_MENU_SUCCESS);
        }catch (RuntimeException e){
            return new Result(false,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_MENU_FAIL);

        }
    }

    /**
     * 动态展示数据+redis缓存
     * @return
     */
    @RequestMapping(value = "/getMenu",method = RequestMethod.GET)
    public Result getMenu(){
        //获取当前用户对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        Map mapMenu = null;
        //查找redis，是否有数据
        byte[] menuBytes = jedisPool.getResource().get("menu".getBytes());
        String username = jedisPool.getResource().get("username");

        try {
            //如果有数据 则返回数据到前端
            if (menuBytes!=null && menuBytes.length>0 && username.length()>0 && username.equals(user.getUsername())){

                //(自定义工具类)反序列化map
                mapMenu = (Map) SerializeUtil.deserialize(menuBytes);
                return new Result(true, MessageConstant.GET_MENU_SUCCESS,mapMenu);

            }
            //如果没有数据或数据有误，则查询数据，存入redis 并返回
            else{
                //动态菜单获取的权限map
                mapMenu = menuService.getMenu(user.getUsername());

                //(自定义工具类)序列化map
                menuBytes = SerializeUtil.serizlize(mapMenu);
                jedisPool.getResource().set("menu".getBytes(),menuBytes);

                //存入最新的username
                jedisPool.getResource().set("username",user.getUsername());

                return new Result(true, MessageConstant.GET_MENU_SUCCESS,mapMenu);

            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MENU_FAIL);
        }
    }
}
